package com.sweetcircle.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sweetcircle.domain.dto.MessageSendDto;
import com.sweetcircle.domain.enums.MessageTypeEnum;
import com.sweetcircle.domain.po.UserContact;
import com.sweetcircle.domain.po.UserInfo;
import com.sweetcircle.exception.BusinessException;
import com.sweetcircle.mapper.UserInfoMapper;
import com.sweetcircle.websocket.MessageHandler;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * &#064;project_name: sweet-circle-server
 * &#064;Author: Anan
 * &#064;time: 2024/8/12 下午8:47
 */

@Service
public class FileServiceImpl implements FileService {


    @Resource
    private UserContactService userContactService;
    @Resource
    private MessageHandler messageHandler;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void avatarUpload(String userId, MultipartFile file,MultipartFile filey) throws Exception {
        String projectPath = System.getProperty("user.dir");
        File filePath = new File(projectPath + "/file/images/avatar");
        File file2 = new File(filePath + File.separator + userId + File.separator + file.getOriginalFilename());
        file.transferTo(file2);

        File file3 = new File(filePath + File.separator + userId + File.separator + "Y_"+file.getOriginalFilename());
        filey.transferTo(file3);
//        String[] suffix = file.getOriginalFilename().split("\\.");

//
//        byte[] data = Files.readAllBytes(file2.toPath());
//        if (data.length == 0){
//            throw new BusinessException(400, "文件上传失败");
//        }
        // byte[] to BufferedImage
//        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
//        BufferedImage image = ImageIO.read(byteArrayInputStream);
        // BufferedImage to byte[]
//        ByteArrayOutputStream baos11 = new ByteArrayOutputStream();
//        ImageIO.write(image, suffix[suffix.length - 1],baos11);
//        byte[] byteArray = baos11.toByteArray();

//        byte[] data11 = AnanUtils.resizeImage(data, suffix[suffix.length - 1],40, 40);
//        File file11 = new File(filePath + File.separator + userId + File.separator + "40_" + file.getOriginalFilename());
//        if (!file11.exists()){
//            file11.createNewFile();
//        }
//        Files.write(file11.toPath(), data11);

//        byte[] data12 = AnanUtils.resizeImage(data, suffix[suffix.length - 1],60, 60);
//        File file12 = new File(filePath + File.separator + userId + File.separator + "60_" + file.getOriginalFilename());
//        if (!file12.exists()){
//            file12.createNewFile();
//        }
//        Files.write(file12.toPath(), data12);

//        byte[] data13 = AnanUtils.resizeImage(data, suffix[suffix.length - 1],100, 100);
//        File file13 = new File(filePath + File.separator + userId + File.separator + "100_" + file.getOriginalFilename());
//        if (!file13.exists()){
//            file13.createNewFile();
//        }
//        Files.write(file13.toPath(), data13);

//        File file11 = new File(filePath + File.separator + userId + File.separator + "40_" + file.getOriginalFilename());
//        Thumbnails.of(file2).size(40, 40).toFile(file11);
//        File file12 = new File(filePath + File.separator + userId + File.separator + "60_" + file.getOriginalFilename());
//        Thumbnails.of(file2).size(60, 60).toFile(file12);

        UserInfo userInfo = new UserInfo();
        userInfo.setAvatar(file.getOriginalFilename());
        int update = userInfoMapper.update(userInfo, new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userId)
                .eq(UserInfo::getStatus, 1));
        if (update < 1){
            throw new BusinessException(400, "用户信息更新失败");
        }

        // 创建联系人 将将添加我为好友的用户的联系人更新
        UserContact userContact = new UserContact();
        userContact.setAvatar(file.getOriginalFilename());

        // 更新 添加我为好友的联系人信息 将我的信息更新到该用户的联系人信息
        boolean update1 = userContactService.update(userContact, new LambdaQueryWrapper<UserContact>()
                .eq(UserContact::getContactUserId, userId)
                .eq(UserContact::getStatus, 1));
        if (!update1){
            throw new BusinessException(400, "联系人信息更新失败");
        }


        // 获取 所有添加我为联系人的用户的userId
        List<String> userIdList = userContactService.list(new LambdaQueryWrapper<UserContact>()
                        .eq(UserContact::getContactUserId, userId)
                        .eq(UserContact::getStatus, 1))
                .stream()
                .map(UserContact::getUserId)
                .toList();

        for (String userId2 : userIdList){  // 遍历所有添加我为联系人的用户的userId
            MessageSendDto messageSendDto = new MessageSendDto<>();
            messageSendDto.setMessageCode(1);
            messageSendDto.setSendUserId(userId);
            messageSendDto.setContactId(userId2);
            messageSendDto.setMessageType(MessageTypeEnum.UPDATE_FRIEND.getType());
            messageHandler.sendMessage(messageSendDto);  // 发送消息告知 联系人信息更新 从新获取联系人
        }

    }
}
